package main

import (
	"context"
	"encoding/json"
	"github.com/go-kit/kit/auth/jwt"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/tracing/opentracing"
	kithttp "github.com/go-kit/kit/transport/http"
	"gysa-share01/common"
	"gysa-share01/exception"
	orderhttp "gysa-share01/order-service/http"
	"gysa-share01/user-service/auth"
	"net/http"
	"os"
)

func main() {
	var (
		orderHttpServer orderhttp.OrderServiceHttpInterface
	)
	reporter, err := common.InitOpTracer("test", "8081")
	defer reporter.Close()
	if err != nil {
		common.Logger.Println(err)
		os.Exit(1)
	}

	orderHttpServer = orderhttp.OrderServiceHttp{}
	payEndpoint := orderhttp.MakeOrderPayEndpoint(orderHttpServer)
	payEndpoint = jwt.NewParser(auth.KeyFunc, auth.JWTMethod, auth.AuthClaimsFactory)(payEndpoint)
	//payEndpoint = jwt.NewSigner("kit", auth.JWTKey,auth.JWTMethod,&auth.AuthClaims{})(payEndpoint)
	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stderr)
		logger = log.With(logger, "ts", log.DefaultTimestampUTC)
		logger = log.With(logger, "caller", log.DefaultCaller)
	}
	payHandle := kithttp.NewServer(
		payEndpoint,
		orderhttp.DecodePayRequest,
		orderhttp.EncodeResponse,
		kithttp.ServerErrorEncoder(errHandler),
		kithttp.ServerBefore(jwt.HTTPToContext()),
		kithttp.ServerBefore(opentracing.HTTPToContext(common.OpTracer, "xxxx", logger)),
	)

	http.Handle("/pay", payHandle)

	http.ListenAndServe(":8084", nil)

}

func errHandler(ctx context.Context, err error, w http.ResponseWriter) {
	w.Header().Set("Content-Type", "application/json;charset=utf-8")
	exceptions, ok := err.(exception.ExceptionInterface)
	resp := common.Response{
		ErrorCode: exception.SYSTEM_ERROR,
		ErrorMsg:  "服务器繁忙",
	}
	if ok && exceptions.ECode() > 0 {
		w.WriteHeader(400)
		resp.ErrorCode = exceptions.ECode()
		resp.ErrorMsg = exceptions.Error()
	} else if isAuthErr(err) {
		w.WriteHeader(403)
		resp.ErrorCode = exception.ACCESS_DENIED
		resp.ErrorMsg = "请先登陆"
	} else {
		common.Logger.Println(err)
		w.WriteHeader(500)
	}
	json.NewEncoder(w).Encode(resp)
}

func isAuthErr(err error) bool {
	if err == jwt.ErrTokenContextMissing {
		return true
	}
	if err == jwt.ErrTokenInvalid {
		return true
	}
	if err == jwt.ErrTokenExpired {
		return true
	}
	if err == jwt.ErrTokenMalformed {
		return true
	}
	if err == jwt.ErrTokenNotActive {
		return true
	}
	if err == jwt.ErrUnexpectedSigningMethod {
		return true
	}
	return false
}
